package com.linghui.videoplus.ipai.adapter;

import java.util.List;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;

import com.linghui.videoplus.ipai.R;
import com.linghui.videoplus.ipai.bean.VideoBean;
import com.linghui.videoplus.ipai.utils.AsyncImageLoader;
import com.linghui.videoplus.ipai.utils.AsyncImageLoader.ImageCallback;
import com.linghui.videoplus.ipai.view.VideoImageListView;

public class VideoImageAdapter extends ArrayAdapter<VideoBean> {
	private ListView listView;
	private AsyncImageLoader asyncImageLoader;

	public VideoImageAdapter(Activity activity, List<VideoBean> videoBean,
			ListView listView) {
		super(activity, 0, videoBean);
		this.listView = listView;
		asyncImageLoader = new AsyncImageLoader();
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		Activity activity = (Activity) getContext();

		View rowView = convertView;
		VideoImageListView viewCache;
		if (rowView == null) {
			LayoutInflater inflater = activity.getLayoutInflater();
			rowView = inflater.inflate(R.layout.adapter_video_image, null);
			viewCache = new VideoImageListView(rowView);
			rowView.setTag(viewCache);
		} else {
			viewCache = (VideoImageListView) rowView.getTag();
		}
		VideoBean vBean = getItem(position);
		String imageUrl = vBean.getImageUrl();
		ImageView imageView = viewCache.getImageView();
		imageView.setMaxHeight(100);
		imageView.setMaxWidth(120);
		imageView.setMinimumHeight(100);
		imageView.setMinimumWidth(120);
		imageView.setScaleType(ImageView.ScaleType.FIT_XY);
		imageView.setTag(imageUrl);
		

		
		Drawable cachedImage = asyncImageLoader.loadDrawable(imageUrl,new ImageCallback() {
			public void imageLoaded(Drawable imageDrawable,String imageUrl) {
				ImageView imageViewByTag = (ImageView) listView.findViewWithTag(imageUrl);
				if (imageViewByTag != null) {
//					imageViewByTag.setBackgroundDrawable(imageDrawable);
					imageViewByTag.setImageDrawable(imageDrawable);
				
				}
			}
		});
		
		if (cachedImage == null) {
			imageView.setImageResource(R.drawable.icon);
		} else {
			imageView.setImageDrawable(cachedImage);
		}

		return rowView;
	}
}
